import requests
import json
import time
import re

from mongo import Mongo
from log import MyLogging

log = MyLogging()


class KuaiShou(object):
    def __init__(self,  cookie):
        self.cookie = cookie
        self.M = Mongo()
        self.history_list = []

    def get_ids(self):
        self.ID_DICT = self.M.get_kusishou_ids()

    def get_video(self, ID):
        json_data = json.dumps(
            {"operationName":"visionProfilePhotoList","variables":{"userId":f"{ID}","pcursor":"","page":"profile"},"query":"query visionProfilePhotoList($pcursor: String, $userId: String, $page: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page) {\n    result\n    llsid\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrl\n        liked\n        timestamp\n        expTag\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"}
        )
        try:
            r = requests.post(
                url="https://video.kuaishou.com/graphql",
                headers={
                    "content-type": "application/json",
                    "Cookie": self.cookie,
                },
                data=json_data
            )
            data = r.json()['data']['visionProfilePhotoList']['feeds']
            log.write_logger(f'{ID} 获取视频成功')
            return data
        except Exception as e:
            log.error_logger(f'{ID} 请求错误 {e}')
            return None

    def parse_data(self, data):
        for i in data:
            h_id = f"{i['author']['id']}_{i['photo']['timestamp']}"
            name = self.filter_emoji(i['author']['name'])
            title = self.parse_title(i['photo']['caption'], name, i['photo']['id'])
            if self.M.get_data(h_id, title):
                continue
            yield {
                "hid": h_id,
                "tag": self.parse_tag(self.ID_DICT[i['author']['id']]['tag'], i['tags']),
                "tid": self.ID_DICT[i['author']['id']]['tid'],
                "platform": self.ID_DICT[i['author']['id']]['platform'],
                "v_id": i['photo']['id'],
                "name": name,
                "desc": '如果有您有想看的(快手 抖音 等)UP请把(他 她 它)的名字发给我，蟹蟹',
                "title": title,
                "video": i['photo']['photoUrls'][0]['url'],
                "img": i['photo']['coverUrl'],
                'timestamp': i['photo']['timestamp']
            }

    def main(self):
        # 重新获取ID
        self.get_ids()
        data_list = []
        for ID in self.ID_DICT:
            result = self.get_video(ID)
            if not result:
                time.sleep(3600)
                continue
            for data in self.parse_data(result):
                yield data
            time.sleep(60)
        return data_list

    def parse_title(self, title, name, v_id):
        ti = title.split('#')
        #  标题重复 or 为空
        if not ti or self.M.get_title(ti[0].strip()):

            return f'{name}：{v_id}'
        return self.filter_emoji(ti[0].strip())

    @staticmethod
    def parse_tag(m_tag, tags):
        try:
            if not isinstance(tags, list):
                return m_tag
            tag = m_tag.split(',')
            tag.extend([i.get('name') for i in tags if i.get('name', '')])
            return ','.join(tag[:6])
        except Exception as e:
            log.error_logger(e)
            return m_tag

    @staticmethod
    def filter_emoji(content):
        try:
            # Wide UCS-4 build
            cont = re.compile(u'['u'\U0001F300-\U0001F64F' u'\U0001F680-\U0001F6FF'u'\u2600-\u2B55]+')
        except re.error:
            # Narrow UCS-2 build
            cont = re.compile(u'('u'\ud83c[\udf00-\udfff]|'u'\ud83d[\udc00-\ude4f\ude80-\udeff]|'u'[\u2600-\u2B55])+')
        return cont.sub(u'', content)


if __name__ == '__main__':
    pass

